package com.zcfeng.ischool;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import org.json.JSONException;
import org.json.JSONObject;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import socket.SocketRunnable;
import utils.MyConstaints;
import utils.SPUtils;
import utils.ToastUtils;

public class LoginActivity extends AppCompatActivity {
    Button login;
    Button regist;
    EditText id;
    EditText pwd;
    MyApp app;
    Handler handler;
    CheckBox isauto;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_login);
        init_handler();
        app= (MyApp) this.getApplication();
        app.addHandle(MyConstaints.login,handler);
        initview();
        initlistenner();
        if(SPUtils.getBoolean(getApplicationContext(),MyConstaints.ISLOGIN,false)){
            isauto.setChecked(true);
            login(SPUtils.getString(getApplicationContext(),MyConstaints.ID,""),SPUtils.getString(getApplicationContext(),MyConstaints.PASSWORD,""));
        }
        else
            isauto.setChecked(false);
    }

    private void init_handler() {
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String str=msg.obj.toString();
                try {
                    JSONObject obj=new JSONObject(str);
                    int code=obj.getInt("code");
                    if(code==200){
                        final String t= (String) obj.getJSONObject("userinfo").get("token");
                        final String name=(String) obj.getJSONObject("userinfo").get("name");
                        final String academy=(String) obj.getJSONObject("userinfo").get("academy");
                        final String professional=(String) obj.getJSONObject("userinfo").get("professional");
                        final String classroom=(String) obj.getJSONObject("userinfo").get("classroom");
                        rongLogin(t, name, academy, professional,classroom);

                    }
                    else{
                        SPUtils.putBoolean(getApplicationContext(),MyConstaints.ISLOGIN,false);
                        SPUtils.putString(getApplicationContext(),MyConstaints.PASSWORD,"");
                        ToastUtils.safeToast(getApplicationContext(),"用户名密码错误");
                        SPUtils.putBoolean(getApplicationContext(), MyConstaints.ISLOGIN,false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }

    public void rongLogin(final String t, final String name, final String academy, final String professional, final String classroom) {
        RongIM.connect(t, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                ToastUtils.safeToast(getApplicationContext(),"登陆失败");

            }
            @Override
            public void onSuccess(String s) {
                if(isauto.isChecked())
                    SPUtils.putBoolean(getApplicationContext(), MyConstaints.ISLOGIN,true);
                else
                    SPUtils.putBoolean(getApplicationContext(), MyConstaints.ISLOGIN,false);
                SPUtils.putString(getApplicationContext(),MyConstaints.ID,id.getText().toString());
                SPUtils.putString(getApplicationContext(),MyConstaints.PASSWORD,pwd.getText().toString());
                SPUtils.putString(getApplicationContext(),MyConstaints.NAME,name);
                SPUtils.putString(getApplicationContext(),MyConstaints.ACADEMY,academy);
                SPUtils.putString(getApplicationContext(),MyConstaints.PROFFESSIONAL,professional);
                SPUtils.putString(getApplicationContext(),MyConstaints.TOKEN,t);
                SPUtils.putString(getApplicationContext(),MyConstaints.CLASSROOM,classroom);
                ToastUtils.safeToast(getApplicationContext(),"登陆成功");
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                finish();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                ToastUtils.safeToast(getApplicationContext(),"登陆失败");
                SPUtils.putBoolean(getApplicationContext(), MyConstaints.ISLOGIN,false);

            }
        });
    }

    private void initlistenner() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uid=id.getText().toString();
                String upwd=pwd.getText().toString();
                login(uid, upwd);

            }
        });
        regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            startActivity(new Intent(LoginActivity.this,RegistActivity.class));
            }
        });
    }

    private void login(String uid, String upwd) {
        JSONObject json=new JSONObject();
        try {
            json.put("type","login");
            json.put("id",uid);
            json.put("pwd",upwd);
            String str=json.toString();
            Message msg=new Message();
            msg.what= MyConstaints.send;
            msg.obj=str;
            app.socket.revHandler.sendMessage(msg);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initview() {
        login= (Button) findViewById(R.id.login);
        regist= (Button) findViewById(R.id.regist);
        id= (EditText) findViewById(R.id.id);
        id.setText(SPUtils.getString(getApplication(),MyConstaints.ID,""));
        pwd= (EditText) findViewById(R.id.pwd);
        pwd.setText(SPUtils.getString(getApplication(),MyConstaints.PASSWORD,""));
        isauto= (CheckBox) findViewById(R.id.isauto);
    }
}
